package com.csl.jsonpreference.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.csl.jsonpreference.R
import com.csl.jsonpreference.bean.ConfigTYPE
import com.csl.jsonpreference.configdes.JsonArrayPreference
import com.csl.jsonpreference.configdes.JsonBasePreference
import com.csl.jsonpreference.configdes.JsonConfigIns
import com.csl.jsonpreference.configdes.JsonObjectPreference
import com.csl.jsonpreference.databinding.FragmentJsonArrayBinding
import com.csl.jsonpreference.util.CLog
import com.csl.ui.utils.colorpicker.ColorPickerDialog
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject

class JsonArrayFragment : Fragment() {


    var viewBinding: FragmentJsonArrayBinding? = null
    var configData: JsonArrayPreference? = null
        set(value) {
            field = value
            lifecycleScope.launchWhenResumed {
                configData?.let {
                    adapter.resetData(it)
                }
//                adapter.resetData(value?.jsonData ?: JSONArray(), value?.getParamsList())
//                adapter.resetData(jsonRootData ?: JSONObject(), value?.getParamsList())
                CLog.d("jsonarray", "刷新配置列表布局: $value")
                adapter.notifyDataSetChanged()
            }
        }
    var jsonRootData: JSONObject? = null

    var adapter = object : JsonArrayAdapter() {
        override fun onPreferenceSelected(index: Int, data: JSONArray, config: JsonConfigIns?) {
            CLog.d("json", "index($index), data:($data), config:($config)")
//            if(index < 0) {
//                viewBinding?.csljsonBtnDelete?.visibility = View.GONE
//                viewBinding?.csljsonBtnEdit?.visibility = View.GONE
//            } else {
//                viewBinding?.csljsonBtnDelete?.visibility = View.VISIBLE
//                viewBinding?.csljsonBtnEdit?.visibility = View.VISIBLE
//            }

            editData(index, data, config)

        }
    }

    var onOpenOrCloseListener: OnOpenOrCloseListener? = null

    fun editData(index: Int, data: JSONArray, config: JsonConfigIns?) {
        when (config?.configType) {

            ConfigTYPE.BOOLEAN -> {
//                    var bData = data.optBoolean(config.key, false)
//                    data.put(config.key, !bData)
                var bData = data.optBoolean(index, false)
                data.put(index, !bData)
                adapter.notifyItemChanged(index)
            }

            ConfigTYPE.ENUM -> {
                if (config is JsonBasePreference) {
                    config.getEnumType()
                    val arrays = config.getEnumType()!!
                    ListChoseDialog<Enum<*>>(
                        title = config.title,
                        content = config.describe,
                        *arrays
                    ) {
                        CLog.d("enum", "选择新枚举:${it} : ${Gson().toJson(it)}")
                        //使用Gson做中转取值
                        var jsonValue = JSONObject()
                        jsonValue.put("value", it)
//                            data.put(config.key, jsonValue.getString("value"))
                        var trueValue = Gson().toJson(it).replace("\"", "")
                        CLog.d("enum", "设置枚举值:${config.key}:${trueValue}")
                        data.put(index, Gson().toJson(it).replace("\"", ""))
//                            data.put(config.key, Gson().toJson(it).replace("\"", ""))
                        adapter.notifyItemChanged(index)
                    }.show(parentFragmentManager, "enumconfig")

                }
            }

            ConfigTYPE.OBJECT -> {
                var groupConfig = config as JsonObjectPreference
                onOpenOrCloseListener?.onGroupOpen(groupConfig)
            }

            ConfigTYPE.COLOR -> {
                var colorDialog = ColorPickerDialog(
                    context,
                    data.optInt(
                        //config.key,
                        index,
                        requireActivity().resources.getColor(R.color.colorPrimary)
                    )
                )
                colorDialog.setOnColorChangedListener {
//                        data.put(config.key, it)
                    data.put(index, it)
                    adapter.notifyItemChanged(index)
                }
                colorDialog.show()
            }

//                ConfigTYPE.ARRAY_BOOLEAN,
//                ConfigTYPE.ARRAY_FLOAT,
//                ConfigTYPE.ARRAY_NUMBER,
//                ConfigTYPE.ARRAY_TXT,
            ConfigTYPE.ARRAY_OBJECT -> {
                var groupConfig = config as JsonArrayPreference
                onOpenOrCloseListener?.onArrayOpen(groupConfig)
            }
//                is EnumPreference -> {
//                    var enumDialog = ListChoseDialog<Enum<*>>(
//                        config.discribe, "",
//                        *config.alltype
//                    ) { it ->
//                        config.value = it
//                        notifyDataSetChanged()
//                        true
//                    }
//                    enumDialog.show(parentFragmentManager, "enumconfig")
//                }

            else -> {
                TxtPreferenceDialog(
                    config?.title ?: "",
                    config?.describe ?: "",
//                        data.optString(config.key, ""),
                    data.optString(index, ""),
                    if (!config?.values.isNullOrEmpty()) {
                        ArrayList<String>().apply {
                            addAll(config!!.values!!)
                        }
                    } else {
                        null
                    }
                ) {
                    when (config?.configType) {
                        ConfigTYPE.FLOAT -> {
                            it.toFloatOrNull()?.let {
//                                    data.put(config.key, it)
                                data.put(index, it)
                                adapter.notifyItemChanged(index)
                            } ?: let {
                                showToast("输入错误, 非浮点数")
                            }
                        }

                        ConfigTYPE.NUMBER -> {
                            it.toIntOrNull()?.let {
//                                    data.put(config.key, it)
                                data.put(index, it)
                                adapter.notifyItemChanged(index)
                            } ?: let {
                                showToast("输入错误, 非数字")
                            }
                        }

                        else -> {
//                                data.put(config.key, "$it")
                            data.put(index, "$it")
                        }
                    }
                    adapter.notifyItemChanged(index)
                }.show(parentFragmentManager, "txtconfig")
            }

        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewBinding = FragmentJsonArrayBinding.inflate(inflater)

        return viewBinding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewBinding!!.rvConfig.layoutManager = LinearLayoutManager(context);
        viewBinding!!.rvConfig.adapter = adapter
        ItemTouchHelper(adapter.drapCallback).attachToRecyclerView(viewBinding!!.rvConfig)

//        viewBinding!!.csljsonBtnEdit.setOnClickListener {
//            var item = adapter.getSelectItem()
//            item?.let {
//                editData(adapter.checkItemIndex, adapter.jsonDatas, item)
//            }
//        }
//        viewBinding!!.csljsonBtnDelete.setOnClickListener {
//            var selectIndex = adapter.checkItemIndex
//            if(selectIndex != -1) {
//                adapter.removeData(selectIndex)
//                viewBinding?.csljsonBtnDelete?.visibility = View.GONE
//                viewBinding?.csljsonBtnEdit?.visibility = View.GONE
//            }
//
//        }

        viewBinding!!.csljsonBtnAdd.setOnClickListener {
            var newItem = configData?.createNewItem()
            CLog.d("addjson", "添加json类型(${newItem?.javaClass}):" + newItem)
            newItem?.let {
                configData?.addNewItem(it)
            }
            adapter.notifyDataSetChanged()
        }

    }


    override fun onDestroyView() {
        super.onDestroyView()
        viewBinding = null
    }

    fun showToast(str: String) {
        lifecycleScope.launchWhenCreated {
            withContext(Dispatchers.Main) {
                Toast.makeText(context, "$str", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onResume() {
        CLog.d("life", "jsonarray resume")
        super.onResume()
    }
}